
import sys
import time
import pygame
from enum import Enum

class EventMouseActionType(Enum):
    PRESSED = 1
    RELEASED = 2

class Window(object):
    def __init__(self, w: int, h: int):
        self.game = pygame
        self.game.init()
        self.width = w
        self.height = h
        self.__title = 'Main Win @ 1.0'
        self.screen = self.game.display.set_mode((self.width, self.height))
        self.screen.fill((255, 255, 255))
        self.elements = []
        self.actions = []
        self.game.display.flip()
        self.game.display.set_caption(self.title)

    @property
    def title(self) -> str:
        return self.__title

    @title.setter
    def title(self, title: str):
        self.__title = title
        # update window title immediately
        self.game.display.set_caption(self.title)

    def addElement(self, obj):
        self.elements.append(obj)

    def addAction(self, ack):
        self.actions.append(ack)

    def update(self):
        need_redraw = False

        for obj in self.elements:
            if obj.dirty:
                # only the screen contain the object which is dirty
                # need redraw the objects
                need_redraw = True
                break

        if True == need_redraw:
            self.cleanScreen()
            for obj in self.elements:
                obj.draw(self)
            # self.game.display.flip()
            self.game.display.update()

    def onMouseAction(self, t: EventMouseActionType, x: int, y: int):
        for obj in self.elements:
            if t == EventMouseActionType.PRESSED:
                obj.onMousePress(x, y)
            elif t == EventMouseActionType.RELEASED:
                obj.onMouseRelease()
                obj.onMouseClick(x, y)

    def onKeyAction(self):
        pass

    def loop(self):
        while True:
            for event in pygame.event.get():
                print('[window]event type = ', event.type)
                if event.type == pygame.QUIT:
                    sys.exit()
                elif event.type == pygame.MOUSEBUTTONDOWN:
                    x, y = event.pos
                    self.onMouseAction(EventMouseActionType.PRESSED, x, y)
                    print('[window]event type = MOUSEBUTTONDOWN', x, y)
                elif event.type == pygame.MOUSEBUTTONUP:
                    self.onMouseAction(EventMouseActionType.RELEASED, x, y)
                    print('[window]event type = MOUSEBUTTONUP')
            for ack in self.actions:
                ack()
            self.update()

    def cleanScreen(self):
        self.screen.fill((255, 255, 255))

    def quit(self):
        pygame.quit()


class Event(object):

    def __init__(self):
        pass

    def onMouseClick(self):
        pass

    def onMousePress(self, x: int, y: int):
        pass

    def onMouseRelease(self):
        pass

    def onKeyClick(self):
        pass

    def onKeyPress(self):
        pass

    def onKeyRelease(self):
        pass
